package com.shangke.corejava.ch14;
/**
 * 使用多线程
 */
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class Chat implements Runnable{
	private Socket socket = null;
	
	public Chat(Socket client) {
		this.socket=client;
	}

	@Override
	public void run() {
		InputStream inputStream=null;
		OutputStream outputStream=null;
		
		try {
			inputStream=socket.getInputStream();
			outputStream=socket.getOutputStream();
			//设置缓存，发送的数据长度不能大于512字节
			byte[] buffer=new byte[512];  //不能超过512个字节，不然会乱码
			
			boolean chatting = true;
			while(chatting){
				//等待并接受客户端发生的数据，有阻塞作用
				int len =inputStream.read(buffer);
				String string=new String(buffer,0,len).trim();
				System.out.println(string);
				
				outputStream.write(("parrot:"+string).getBytes());
				if ("quit".equalsIgnoreCase(string)) {
					chatting=false;
				}
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				
			}
			try {
				if (outputStream != null) {
					outputStream.close();
				}
			} catch (IOException e) {
				
			}
			try {
				if (socket != null) {
					socket.close();
				}
			} catch (IOException e) {
				
			}
		}
		
	}

}
